/* ----------------------------------------------------------------------------

	pax.load.js Copyright (C) 2006, 2008 Mikkel Bergmann, Pointful

	Licence
	-------
	
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

	See lgpl.txt for licence details

---------------------------------------------------------------------------- */


/*
	Script: pax.load
		This is library can detect when the complete DOM has been rendered. It can also load PAX scripts on the fly
		
	Author:
		Mikkel Bergmann, <http://www.pointful.com>

*/


/*	Property: pax.load
		This library OBJ	*/
var pax = pax || {};
pax.load = pax.load || {};

/*	Property: pax.load.docLoaded
		True if the document DOM has loaded (excluding images and sub-documents).	*/
pax.load.docLoaded = false;
/*	Property: pax.load.docLoadedFuncs
		List of functions to run when the document has loaded	*/
pax.load.docLoadedFuncs = [];

//	Loads a script, and cache it, optionally calling the callback function
//	Note: you should use pax.load.script.
pax.load.cacheScript = function( url, callback ) {
	var script = pax.cache.get( url );
	if( script ) {
		if( pax.util.getType( callback ) == 'function' )callback();
	} else {
		var initLibrary = function( xml, txt, url ) {
			if( window.execScript ) { window.execScript( txt ); }	// eval in global scope for IE, otherwise everyone else.
			else if( window.eval ) { window.eval( txt ); }
			else { eval( txt ); }
			pax.cache.set( url, txt, 0 );
			if( pax.util.getType( callback ) == 'function' )callback();
		};
			
		/*
			See if we are in a frame, try and use the parent frames PAX to cache the 
			script, this is VERY beneficial for HTTPS applications, as HTTPS does NOT
			cache javascript, so to use this:
			1. Create an iFrame "shell", in which the parent holds JS in cache
			2. The child frame contains the web application. 
			3. Use pax.load.script to load javascripts, and run the code
		*/
		var topWin = window.top;
		if( topWin && ( topWin != window.self ) && topWin.pax ) {
			//	Get the script from the parent's cache.
			var scriptRO = topWin.pax.load.cacheScript( url, function () {
				script = topWin.pax.cache.get( url );
				initLibrary( '', script, url );
			} );
			
		} else {
			pax.post( url, '', initLibrary, 'pax.load.script', null, null );
		}
	}
};


/*	Method: pax.load.script
	Loads a list of scripts, then calls the callback
	
	Parameters:
		list - list of scripts that we want to load, this can be either the complete or relative path
		callback - a function to run, when the scripts have loaded
		
	Example:
		(start code)
			<span id="pax.script.example1">You should see a message pop up, then disappear after 5 seconds here: </span>
			[:.
				function showWindowAfterLoad() {
					pax.box.showOnRight( 'myBox', 'This box is rendered via an asynchronously loaded library', 'hintMessage', pax.$('pax.script.example1'), 5 );
				}
				
				pax.load.script( '/pax/pax.box.js', showWindowAfterLoad );
			:]
		(end)
		Loads the <pax.box> library via ajax, and uses it to display a message box using <showBox>.
*/
pax.load.script = function( list, callback ) {
	if( pax.util.getType( list ) != 'array' )list = [list];
	if( list.length > 1 ) {
		pax.load.cacheScript( list[0], function() { pax.load.script( list.slice(1), callback ) } );
	} else {
		pax.load.cacheScript( list[0], callback );
	}
};


/*	Method: pax.load.css
	Load CSS via ajax, and runs the callback when done.
	
	Parameters:
		url - The URL of the CSS you want to load
		callBack - The method to run when the CSS has been loaded

	Example:
		(start code)
			[:.
				pax.load.css( '/pax/resource/pax_consolidated.css', function() { alert('Loaded CSS.'); } );
			:]
		(end)
		Loads some CSS, and alerts when done.

*/
pax.load.css = function( url, callBack ) {
	var initCSS = function( xml, txt, url ) {
		if( ( url.indexOf( '.css' ) != -1 ) && ( url.lastIndexOf( '.css' ) == url.length - 4 ) ) {
			myCSS = document.createElement( 'link' );
			myCSS.setAttribute( 'rel', 'stylesheet' );
			myCSS.setAttribute( 'type', 'text/css');
			myCSS.setAttribute( 'href', url );
			document.getElementsByTagName("head").item(0).appendChild( myCSS );
		};
		callBack();
	};
	pax.post( url, '', initCSS, 'pax.load.css', null, null );
};


/*	Method: pax.load.onloaded
	Binds a function to launch when the DOM document is ready (excluding loading images and sub-documents); launches the function immediately if document is ready.
	
	Parameters:
		func - Function that runs when the event fires

	Example:
		(start code)
			var myFunc = function() {
				alert('hello world!');
			}
			pax.load.onloaded( myFunc );
		(end)
		Will alert when the DOM has loaded. Note that the example won't run, as the document has already loaded
*/
pax.load.onloaded = function( func ) {
	if( pax.load.docLoaded )return func.apply( document, [pax] );
	else pax.load.docLoadedFuncs.push( function() { return func.apply( this, [pax]) } );
};

/*	Private Method: pax.load.initOnload
	This method fires when the DOM document is ready (excluding loading images and sub-documents). This is a private method only, it will run every function added using the <pax.load.onloaded> method.
*/
pax.load.initOnload = function() {
	if( ! pax.load.docLoaded ) {
		// kill the timer
		if( pax.load.safariOnloadTimer ) {
			clearInterval( pax.load.safariOnloadTimer );
			pax.load.safariOnloadTimer = null;
		}
		for( var f = 0; f < pax.load.docLoadedFuncs.length; f++ ) {
			pax.load.docLoadedFuncs[f]();
		}
		pax.load.docLoadedFuncs = [];
		pax.load.docLoaded = true;
		if( document.removeEventListener )document.removeEventListener( "DOMContentLoaded", pax.load.initOnload, false );
	}
};

/*
	Based on: http://www.hedgerwow.com/360/dhtml/ie-dom-ondocumentready.html
	
	The following bit of code launches as the browser DOM has loaded, rather 
	than as the whole document (including images) has loaded.
	
	Use pax.load.onloaded to add a function to the list that is executed as this event fires.
*/
(	function() {
		var u =navigator.userAgent;
		var e=/*@cc_on!@*/false;
		if(/webkit/i.test(u)){
			setTimeout(function(){
				var dr=document.readyState;
				if(dr=="loaded"||dr=="complete"){
					pax.load.initOnload(); // call the onload handler
				}else{
					setTimeout(arguments.callee,12);
					pax.load.hasInitialisedOnloaded = true;
			}},12);
		} else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){
			document.addEventListener("DOMContentLoaded",pax.load.initOnload,false);
		} else if(e){
			(function(){
				var t=document.createElement('doc:rdy');
				try{
					t.doScroll('left');
					pax.load.initOnload();
					t=null;
				}catch(e){
					setTimeout(arguments.callee,0);
				}})();
		}else {
			if( ! pax.load.hasInitialisedOnloaded )window.onload=pax.load.initOnload;
		}
	}
)();